﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ThreeByte.ActiveDeck.Data;
using log4net;
using System.Text.RegularExpressions;
using ThreeByte.ActiveDeck.Service;

namespace ThreeByte.ActiveDeck.Web.console
{
    public partial class ForgotPassword : System.Web.UI.Page
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(ForgotPassword));

        protected void Page_Load(object sender, EventArgs e) {

            SubmitButton.Attributes.Add("onmouseover", "this.src='./skins/images/Submit_on.png'");
            SubmitButton.Attributes.Add("onmouseout", "this.src='./skins/images/Submit_off.png'");
            
        }

        private static readonly Regex EMAIL_REGEX = new Regex(@"^(?("")("".+?""@)|" +
                                                               @"(([0-9a-zA-Z]((\.(?!\.))|" +
                                                               @"[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" +
                                                               @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|" +
                                                               @"(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$");

        protected void SubmitButton_Click(object sender, ImageClickEventArgs e) {
            //Get the email address
            string emailAddress = EmailText_Box.Text;
            
            //Test if it is valid email
            if(!(EMAIL_REGEX.Match(emailAddress).Success)) {
                //This does not look like a real email address
                EmailText_Box.BorderWidth = 3;
                ErrorLabel.Text = "Please enter a valid email address";
                ResultLabel.Text = null;
                EmailText_Box.Focus();
                return;
            }
            
             //Looks like a valid email
            EmailText_Box.Text = null;
            EmailText_Box.BorderWidth = 0;
            ErrorLabel.Text = null;

            //Register a reset request
            Guid resetKey = DataUtil.RequestPasswordReset(emailAddress);
            EmailUtil.SendPasswordResetEmail(emailAddress, resetKey);

            //Change the UI to reflect
            ResultLabel.Text = "Please check your email for instructions to finish resetting your password.";

        }
    }
}